/*
 * 14. Write a program that reads two integers n
 * and m and a matrix of integers of size n * m
 * and finds in the matrix the biggest
 * rectangular area of equal cells.
 * 
 * Алгоритъмът е тромав и еднопосочен – 
 * не намира винаги търсения блок.
 */

package _3;

import java.util.Scanner;

public class _14 {
	public static int input (Scanner scn) {
		if (!scn.hasNextInt ()) {
			System.err.println ("error: mismatched input");
			System.exit (1);
		}

		return scn.nextInt ();
	}

	public static void main (String[] args) {
		Scanner scn = new Scanner (System.in);

		System.out.print ("n ?= ");
		int n = input (scn);
		System.out.print ("m ?= ");
		int m = input (scn);

		int[][] matrix = new int[n][m];
		int bCount = 0, bi = 0, bj = 0, bCol = 0, bRow = 0;
		int col, row = 0, ptr;

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				System.out.printf ("matrix[%d][%d] ?= ", i, j);
				matrix[i][j] = input (scn);
			}
		}

		System.out.println ("matrix:");
		for (int i = 0; i < n; i++) {
			System.out.print ('|');

			for (int j = 0; j < m; j++) {
				System.out.printf ("%2d|", matrix[i][j]);
				int k, l, tmp;

				col = 0;
				ptr = matrix[i][j];
				for (k = i; k < n && matrix[k][j] == ptr; k++, col++) {
					for (l = j, tmp = 0; l < m && matrix[k][l] == ptr; l++, tmp++)
						;

					if (k == i)
						row = tmp;
					else if (tmp < row)
						row = tmp;
				}

				tmp = col * row;
				if (tmp > bCount) {
					bCount = tmp;
					bi = i;
					bj = j;
					bRow = row;
					bCol = col;
				}

				row = 0;
				ptr = matrix[i][j];
				for (k = j; k < m && matrix[i][k] == ptr; k++, row++) {
					for (l = i, tmp = 0; l < n && matrix[l][k] == ptr; l++, tmp++)
						;

					if (k == j)
						col = tmp;
					else if (tmp < col)
						col = tmp;
				}

				tmp = col * row;
				if (tmp > bCount) {
					bCount = tmp;
					bi = i;
					bj = j;
					bRow = row;
					bCol = col;
				}
			}

			System.out.println ();
		}

		System.out.println ("\nmatch:");
		for (int i = bi; i < bi + bCol; i++) {
			System.out.print ('|');
			for (int j = bj; j < bj + bRow; j++) {
				System.out.printf ("%2d|", matrix[i][j]);
			}
			System.out.println ();
		}
	}
}